package drds.plus.executor.function.aggregate_function;

import drds.plus.executor.ExecuteContext;
import drds.plus.sql_process.type.Type;

public class Sum extends AggregateFunction {

    public Sum() {
    }

    public void map(ExecuteContext executeContext, Object[] args) {
        doSum(args);
    }

    public void reduce(ExecuteContext executeContext, Object[] args) {
        doSum(args);
    }

    private void doSum(Object[] args) {
        Object arg = args[0];

        if (arg == null)
            return;
        Type type = this.getMapReturnType();

        if (result == null) {
            arg = type.convert(arg);
            result = arg;
        } else {
            result = type.getCalculator().add(result, arg);
        }

    }

    public int getArgSize() {
        return 1;
    }

    public Type getReturnType() {
        return this.getMapReturnType();
    }

    public Type getMapReturnType() {
        return Type.BigDecimalType;
    }

    public String[] getFunctionNames() {
        return new String[]{"sum"};
    }
}
